// pages/release/release.js
import Toast from 'tdesign-miniprogram/toast/index';
import { apiPublishComment ,apigetCommentById,apiSelectReplys,deleteComment,likeComment,apiGetSchoolInfo} from '../../../utils/http/api'
import evn from "../../../utils/http/evn"
const dictionary = wx.getStorageSync('allDicData')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    userInfo: {},
    url: '',
    originFiles: [
    ],
    gridConfig: {
      column: 3,
      width: 200,
      height: 200,
    },
    config: {
      count: 1,
    },
    form: {
      title: '',
      content: '',
      commentFiles: []
    },
    userInfo: {},
    disabled: true,
    visible: false,
    schoolId: 0,
    schoolName: '',
    proId: '',
    proNameCn: '',
    type:0,
    comment:null,
    visible:false,
    replyInfo:null,
    replyList:null,
    likeCount:0,
    commentCount:0,
    eduPlanName:'',
    schoolInfo:null,
    isMultiLine: false,  // 控制输入框是单行还是多行模式
    commentContent: '',  // 评论内容
    keyboardHeight: 0,   // 键盘高度
    // 图片预览
    viewerVisible: false,
    viewerImages: [],
    viewerIndex: 0,
  },


  // 跳转个人信息页
  goPersonal() {
    wx.reLaunch({
      url: '/pages/personal/personal',
    })
  },

  // 打开图片预览
  openImageViewer(e) {
    const { urls, index } = e.currentTarget.dataset;
    const images = Array.isArray(urls) ? urls : (typeof urls === 'string' ? urls.split(',') : []);
    this.setData({
      viewerVisible: true,
      viewerImages: images,
      viewerIndex: Number(index) || 0,
    });
  },

  // 预览显隐变化（遮罩点击、手势关闭等）
  onViewerVisibleChange(e) {
    const { visible } = e.detail || {};
    if (typeof visible === 'boolean') {
      this.setData({ viewerVisible: visible });
    }
  },

  // 点击关闭按钮
  onViewerClose() {
    this.setData({ viewerVisible: false });
  },

  closeDialog() {
    this.setData({
      visible: false,
    });
    // 返回上一页
    wx.navigateBack()
  },


  onChangeT(e) {
    let title = this.data.form.title
    let content = this.data.form.content
    this.setData({
      'form.title': e.detail.value,
      disabled: title === '' || content === '' ? true : false
    })
  },

  onChangeC(e) {
    let title = this.data.form.title
    let content = this.data.form.content
    this.setData({
      'form.content': e.detail.value,
      disabled: title === '' || content === '' ? true : false
    })
  },
  handleSuccess(e) {
    const { files } = e.detail;
    //如果文件大小超过1m .则压缩文件在1m内
    //循环处理每个文件
    files.forEach((item) => {
      if (item.size > 1024 * 1024) {
        wx.compressImage({
          src: item.url, // 图片路径
          quality: 80, // 压缩质量
          success: (res) => {
           //增加这个图片进originFiles
            this.setData({
              originFiles: this.data.originFiles.concat({ url: res.tempFilePath, name: item.name, type: item.type }),
            });
          }
        })
      } else {
        //不重复的增加进originFiles
        if (this.data.originFiles.findIndex((v) => v.url === item.url) === -1) {
          this.setData({
            originFiles: this.data.originFiles.concat(item),
          });
        }
      }
  
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    //压缩图片大小宽度在1024内
  },

  getSchoolInfo(schoolId){
    let param ={
        schoolId:schoolId
    }
    apiGetSchoolInfo(param).then((res)=> {
     // var resData = JSON.parse(res.data)
      if(res.code==200){
        this.setData({
          schoolInfo:res.data,
          eduPlanName:this.getDictLabel("edu_plan",res.data.eduPlanId)
        })
      }
    })
  },

  getDictLabel(dicname,value){
    let dic = dictionary[dicname]
    let obj = dic.find((elem)=> elem.dictValue==value)
    if (obj) {
      return obj.dictLabel
    }else{
      return ''
    }
  },



  // 上传图片 
  upImages(item) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: evn.dev.baseUrl + '/usercomments/uploadFile',
        filePath: item.url,
        name: 'file',
        success: (res) => {
          var resData = JSON.parse(res.data)
          if(resData.code!=200){
            Toast({
              context: this,
              selector: '#t-toast',
              message: '图片违规，请重新选择图片',
              theme: 'warning',
              direction: 'column',
            });
            this.setData({
              loadingFlag: false,
              originFiles: [],
            })
            this.data.form.commentFiles=[]
            reject() 
            return
          }
          this.data.form.commentFiles.push(resData.fileUrl);
          resolve(); // 表示上传完成
        },
        fail: (err) => {
          reject(err); // 表示上传失败
        }
      });
    });
  },

  // 发布讨论
  async insertCommentInfo() {
    this.setData({
      loadingFlag: true
    })
    let originFiles = this.data.originFiles;
    try {
      // 如果有图片待上传，展示全局加载提示
      if (originFiles && originFiles.length > 0) {
        wx.showLoading({ title: '图片上传中...', mask: true });
      }
      // 上传所有图片并获取上传完成的Promise数组
      let uploadPromises = originFiles.map((item) => this.upImages(item));
      console.log("uploadPromises"+uploadPromises)
      await Promise.all(uploadPromises); // 等待所有图片上传完成
      console.log("files_length:"+this.data.form.commentFiles.length)
      // 上传完成后提示
      if (originFiles && originFiles.length > 0) {
        wx.hideLoading();
        wx.showToast({ title: '图片上传完成', icon: 'success', duration: 1500 });
      }
      let filesStr="";
      if (this.data.form.commentFiles.length > 0) {
         filesStr = this.data.form.commentFiles.join(',')
      }
      let params = {
        objectId: this.data.schoolId,
        title: this.data.form.title,
        content: this.data.form.content,
        wechatUserId: this.data.userInfo.id,
        pics: filesStr,
        type:Number(this.data.type)
      };
      if (params.title && params.content) {
        // 所有图片上传完成后，执行apiInsertCommentInfo方法
        let result = await apiPublishComment(params);
        if (result.code===200) {
          // 发布成功，取消加载状态
          this.setData({ loadingFlag: false })
          wx.navigateBack()
        }else if (result.code===7){
          Toast({
            context: this,
            selector: '#t-toast',
            message: '内容含有敏感词，请重新填写',
            theme: 'warning',
            direction: 'column',
          });
          this.setData({
            loadingFlag: false
          })
        }
      } else {
        if (!params.title) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请输入标题',
            theme: 'warning',
            direction: 'column',
          });
        }
        else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请输入内容',
            theme: 'warning',
            direction: 'column',
          });
        }
      }
      
    } catch (error) {
      // 发生错误时关闭加载提示
      try { wx.hideLoading(); } catch (e) {}
      this.setData({ loadingFlag: false })
    }
    
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if( wx.getStorageSync('userInfo')==null){
      wx.reLaunch({
        url: '/pages/login/login',
      })
    }

    this.setData({
      id :options.id,
      schoolId: options.schoolId,
      userInfo:wx.getStorageSync('userInfo')
    })
 
    let params = {
      id : options.id
    }
    apigetCommentById(params).then((res)=> {
      res.comment.createdAt =this.getTimeDescription(res.comment.createdAt)
      res.comment.nickName=res.comment.nickName==null || res.comment.nickName=='' ?'匿名用户':res.comment.nickName
      this.setData({
        comment: res.comment,
        likeCount:res.likeCount,
        commentCount:res.replyCount
      })
      this.getSchoolInfo(res.comment.objectId)
    })
    this.getReplys()

  },
  
  // 时间处理
  getTimeDescription(datetime) {
    const currentTime = new Date();
    const targetTime = new Date(datetime);
    const timeDiff = currentTime.getTime() - targetTime.getTime();
    const minutes = Math.floor(timeDiff / (1000 * 60));
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
  
    if (minutes < 5) {
      return '刚刚';
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 10) {
      return `${days}天前`;
    } else {
      const month = targetTime.getMonth() + 1;
      const day = targetTime.getDate();
      return `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }
  },

  reply(e){
    //console.log("commentContent"+this.data.commentContent)
    this.setData({
      replyInfo:'',
      commentContent: '',  // 清空评论内容
      isMultiLine: false   // 默认使用单行输入框
    })
    this.setData({
      'replyInfo.id':e.currentTarget.dataset.id,
    })
    this.setData({ visible: true, replyInfo:'' });
    
    // 监听键盘高度变化
    this.watchKeyboard();
  },
  
  // 监听键盘高度变化
  watchKeyboard() {
    wx.onKeyboardHeightChange(res => {
      this.setData({
        keyboardHeight: res.height
      });
    });
  },
  onVisibleChange(e) {

    this.setData({
      visible: e.detail.visible
    });
  },
  hideReplyBar() {
    this.setData({ 
      visible: false,
      commentContent: '',  // 清空评论内容
      keyboardHeight: 0
    });
    // 取消监听键盘高度变化
    wx.offKeyboardHeightChange();
  },
  stopTap() {
    // 阻止事件冒泡，防止点击输入框时关闭
  },
  
  // 切换输入框模式（单行/多行）
  toggleInputMode() {
    this.setData({
      isMultiLine: !this.data.isMultiLine
    });
  },

  onInput: function(e) {
    const { name } = e.currentTarget.dataset;
    console.log("name"+name)
    this.setData({
      [name]: e.detail.value
    });
  },

  fabu(){
    if(this.data.commentContent==""){
      wx.showToast({
        title: '内容不能为空',
      })
      return;
    }
    let param ={
      objectId:this.data.schoolId,
      wechatUserId:this.data.userInfo.id,
      content:this.data.commentContent,
      parentId:this.data.comment.id,
      type:2
    }

    apiPublishComment(param).then((res)=> {
      if (res.code===200) {
        this.getReplys()
        this.setData({
          visible: false,
          commentContent: '',
          isMultiLine: false,
          keyboardHeight: 0
        })
        // 取消监听键盘高度变化
        wx.offKeyboardHeightChange();
      }else if (res.code===7){
        Toast({
          context: this,
          selector: '#t-toast',
          message: '内容含有敏感词，请重新填写',
          theme: 'warning',
          direction: 'column',
        });
      }
    })

  },

  // 查询讨论列表
  getReplys(){
    this.setData({
      loadingFlag: true
    })
    let params = {
      pageNum: 1,
      pageSize: 10,
      parentId:this.data.id,
      wechatUserId:this.data.userInfo.id
    }
    apiSelectReplys(params).then((res)=> {
     
      if (res.data && res.data.length) {
        res.data = res.data.map((item)=> {
          item.createdAt = this.getTimeDescription(item.createdAt)
          item.nickName=item.nickName==null || item.nickName=='' ?'匿名用户':item.nickName
          return item
        })
        this.setData({
          replyList: res.data
        })
      }
      else {
        this.setData({
          replyList: []
        })
      }
    })
  },

  deleteComment(e){
    console.log(e.currentTarget.dataset.userid)
    //不能删除别人的评论
    if (e.currentTarget.dataset.userid !== this.data.userInfo.id) {
      return
    }
    //提醒是否删除
    wx.showModal({
      title: '提示',
      content: '确定要删除该评论吗？',
      success: (res) => {
        if (res.confirm) {
          let params = {
            id: e.currentTarget.dataset.id
          }
          deleteComment(params).then((res)=> {
            if (res.code===200) {
              this.getReplys()
            }else{
              wx.showToast({
                title: '删除失败',
              })
            }
          })
        }
      }
    })
  },

  // 点赞
  addLike(e) {
    let commentId = e.currentTarget.dataset.id
    let type = e.currentTarget.dataset.type
    let params = {
      commentId, // 讨论Id
      wechatUserId: this.data.userInfo.id, //点赞人id
      type  //1是点赞，0是取消点赞
    }
    likeComment(params).then((res)=> {
      let list = this.data.replyList
      let indexs = ''
      list.forEach((item, index)=>{
        if (item.id===commentId) {
          indexs = index
        }
      })
      list[indexs].isLike =type
      if (list[indexs].isLike === 1) {
        ++list[indexs].likeCount
      }
      else {
        --list[indexs].likeCount
      }
      this.setData({
        replyList:list
      })

    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})